
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>SpringBoot实现广播式WebSocket</title>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
	<noscript>
		<h2 style="color: #ff0000">抱歉,您的浏览器不支持改功能!</h2>
	</noscript>
	<div>
		<div>
			<button id="connect" onclick="connect();">连接</button>
			<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
		</div>
		<div id="conversationDiv">
			<label>请输入您的姓名</label><input type="text" id="name" />
			<button id="sendName" onclick="sendName();">发送</button>
			<p id="response"></p>
		</div>
	</div>
</body>
<script type="text/javascript">
	var stompClient = null;

	function setConnected(connected) {
		document.getElementById('connect').disabled = connected;
		document.getElementById('disconnect').disabled = !connected;
		document.getElementById('conversationDiv').style.visibility = connected ? 'visible'
				: 'hidden';
		$("#response").html();
	}

	function connect() {
		var socket = new SockJS('/endpointAric'); //连接SockJS的endpoint名称为"endpointWisely"
		stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
		stompClient.connect({}, function(frame) {//连接WebSocket服务端
			setConnected(true);
			console.log('Connected:' + frame);
			//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息,这个是在控制器的@SentTo中定义的
			stompClient.subscribe('/topic/getResponse', function(response) {
				showResponse(JSON.parse(response.body).responseMessage);
			});
		});
	}

	function disconnect() {
		if (stompClient != null) {
			stompClient.disconnect();
		}
		setConnected(false);
		console.log("Disconnected");
	}

	function sendName() {
		var name = $("#name").val();
		//通过stompClient.send向/welcome 目标(destination)发送消息,这个是在控制器的@MessageMapping中定义的
		stompClient.send("/app/welcome", {}, JSON.stringify({
			'name' : name
		}));
	}

	function showResponse(message) {
		var response = $("#response");
		response.html(message);
	}
</script>
</html>